//
//  PlazaChatController.swift
//  NDAi
//
//  Created by 丸子 on 2024/6/28.
//

import UIKit
import IQKeyboardManagerSwift

class PlazaChatController: BaseViewController {
    var model = PlazaListModel()
    let viewModel = PlazaChatViewModel()
    let disposeBag = DisposeBag()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.keyboardDistanceFromTextField = -bottomSafeAreaHeight
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        viewModel.stopTimer()
        IQKeyboardManager.shared.keyboardDistanceFromTextField = -(kMusicBarHeight - 13)
    }
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = UITableView.automaticDimension
//        tableView.register(cellWithClass: HomeTipsCell.self)
        tableView.register(cellWithClass: HomeMessageCell.self)
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 100, right: 0)
        return tableView
    }()
    
    lazy var inputViwe: HomeInputVIew = {
        let view = HomeInputVIew()
        return view
    }()
 
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = model.title ?? ""
        self.viewModel.dataId = "\(self.model.id ?? 0)"
        self.viewModel.question = self.model.item?.first?.question
        self.viewModel.answer = self.model.item?.first?.answer
        self.view.backgroundColor = UIColor(hexString: "#F3F2F7")
        self.view.addSubview(tableView)
        view.addSubview(inputViwe)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(self.safeTop)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(self.safeBottom)
        }
        inputViwe.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(56 + bottomSafeAreaHeight)
        }
        inputViwe.sendBtn.setClosureTouchUpInside_k { [weak self] in
            self?.sendMessage()
        }
        bindEvent()
        self.viewModel.getDataSource()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
    }
    
    func bindEvent(){
        self.viewModel.messageEventSubject.subscribe(onNext: { [weak self] code, msg in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.tableView.reloadData()
                if code == 1 { //滚动到底部
                    self.scrollToBottom()
                }else if code == -1 {//隐藏键盘
                    kHideKeyboard()
                }
                if let msg = msg {
                    NDProgressHUD.show(message: msg)
                }
            }
        }).disposed(by: disposeBag)
        
        viewModel.messageStateSubject.subscribe(onNext: { [weak self] in
            guard let self = self else { return }
            self.inputViwe.sendBtn.isSelected = self.viewModel.isGenerated
        }).disposed(by: disposeBag)
    }
    
    func sendMessage(){
        if self.viewModel.isGenerated {
            NDProgressHUD.show(message: "请等待回复后再发送")
            return
        }
        if let text = inputViwe.inputFiled.text, text.count > 0 {
            self.inputViwe.inputFiled.text = ""
            kHideKeyboard()
            self.viewModel.checkWords(message: text)
        }else {
            NDProgressHUD.showSuccess(title: "", subtitle: "请输入你想问的问题!")
        }
    }
    
    func scrollToBottom() {
        tableView.reloadData()
        do {
            if viewModel.messageList.count >= 1 {
                let indexPath = IndexPath(row: viewModel.messageList.count - 1, section: 0)
                tableView.scrollToRow(at: indexPath, at: .bottom, animated: false)
            }
        } catch {
            // Handle any potential exceptions here
        }
    }

}
extension PlazaChatController: UITableViewDelegate, UITableViewDataSource {
   
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.messageList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = self.viewModel.messageList[indexPath.item]
        let cell = tableView.dequeueReusableCell(withClass: HomeMessageCell.self)
        cell.setup(message: model)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
}
